<?php
/**
 * Stream控制器负责网站关于时间线、列表的所有功能。
 * 这是责任链模式中的命令链类，用于向所有注册的服务依次发送命令请求，直到有服务响应。
 * @author Clippit
 *
 */
 
if ( !function_exists('mb_strlen') ) {
	function mb_strlen ($text, $encode) {
		if ($encode=='UTF-8') {
			return preg_match_all('%(?:
					  [\x09\x0A\x0D\x20-\x7E]           # ASCII
					| [\xC2-\xDF][\x80-\xBF]            # non-overlong 2-byte
					|  \xE0[\xA0-\xBF][\x80-\xBF]       # excluding overlongs
					| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
					|  \xED[\x80-\x9F][\x80-\xBF]       # excluding surrogates
					|  \xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
					| [\xF1-\xF3][\x80-\xBF]{3}         # planes 4-15
					|  \xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
					)%xs',$text,$out);
		}else{
			return strlen($text);
		}
	}
}

class StreamController extends Controller
{
	private $_services = array ();
	private $userid;
	private $services;
	public function StreamController(){
		$this->userid=Yii::app()->user->id;
		$this->services=Services::model()->findAll("user_id=?",array($this->userid));
	}

	/**
	 * 注册一个服务
	 * @param Service $service
	 */
	public function addService($service) {
		
		$this->_services [] = $service;
	}

	public function makeStream($page = 0) {
		
		$stream = array ();
		
		foreach ($this->services as $s){
		
			$service=new $s->type($s->param1,$s->param2);

			$this->addService($service);
		}
		foreach ( $this->_services as $s ) {
			try {
				$single_stream = $s->getLatest(10, $page);
				Yii::trace(print_r($single_stream, TRUE));
				$stream=array_merge($stream, $single_stream) ;
			} catch ( Exception $e ) {
				echo 'Caught exception: ', $e->getMessage(), "\n";
				return;
			}
		}
		usort($stream,array("StreamController","sortByTime"));
		//print_r($stream);
		return $stream;
	}
	
	private function sortByTime($a, $b) {
		return $b ['datetime'] - $a ['datetime'];
	}

	public function actionUpdate() {
		if (isset($_POST['status'])) {
			$content = $_POST['status'];
			$service = split("\|", $_POST['services']);
			foreach($service as $id) {
				$servicename = Services::model()->findByPk($id);
				$type = $servicename->type;
				//echo $type;
				$service = new $type($servicename->param1, $servicename->param2);
				try {
					if ($service->update($content))
						return;
				} catch ( Exception $e ) {
					echo 'Caught exception: ', $e->getMessage(), "\n";
				}
			}
			return;
		}
	}

	public function reply($target, $id, $content, $reply_to = null) {
		foreach ( $this->_services as $s ) {
			try {
				if ($s->reply($target, $id, $content, $reply_to))
					return;
			} catch ( Exception $e ) {
				echo 'Caught exception: ', $e->getMessage(), "\n";
			}
		}
	}
	

	public function getProfile($target, $uid) {
		foreach ( $this->_services as $s ) {
			try {
				if (($r = $s->getProfile($target, $uid)) != FALSE)
					return $r;
			} catch ( Exception $e ) {
				echo 'Caught exception: ', $e->getMessage(), "\n";
			}
		}
	}
	public function actionFeed()
	{
		$feed=$this->makeStream();
		
		foreach ($feed as $s){
			$s['content'] = preg_replace ('/(^|[^\"\'\]])(http|ftp|https)\:\/\/([^\s\[\]\"\'\(\)<（）。，]+)/', '$1<a href="$2://$3" target="_blank">$2://$3</a>', $s['content']);
			echo "<div class='sweet ".$s['source']." clearfix'>";
			echo "<div class='avatar'><img src='".$s['avatar']."'></img></div>";
			echo "<div class='feed_content'>";
			echo "<div class='feeder_name'>".$s['user'].":</div>";
			echo "<div class='feeder_say'>".$s['content']."</div>";
			echo "<div class='feed_info'>".date('Y-m-d H:i:s',$s['datetime'])."</div>";
			echo "</div></div>";
		}

	}
	
	public static function deleteLong($element) {
		if ( mb_strlen(strip_tags(strval($element['content']))) < 100) {
			//echo 'delete' . $element['content'] . '<br/>';
			return FALSE;
		} else {
			return TRUE;
		}
	}
	public function actionFeedLong() {
		$i = 0;
		$feed_long = array();
		while(count($feed_long) < 20) {
			$feed=$this->makeStream($i++);
			$feed = array_filter($feed, array('StreamController','deleteLong'));
			$feed_long = array_merge($feed_long, $feed);
		}
		
		foreach ($feed_long as $s){
			$s['content'] = preg_replace ('/(^|[^\"\'\]])(http|ftp|https)\:\/\/([^\s\[\]\"\'\(\)<（）。，]+)/', '$1<a href="$2://$3" target="_blank">$2://$3</a>', $s['content']);
			echo "<div class='sweet ".$s['source']." clearfix'>";
			echo "<div class='avatar'><img src='".$s['avatar']."'></img></div>";
			echo "<div class='feed_content'>";
			echo "<div class='feeder_name'>".$s['user'].":</div>";
			echo "<div class='feeder_say'>".$s['content']."</div>";
			echo "<div class='feed_info'>".date('Y-m-d H:i:s',$s['datetime'])."</div>";
			echo "</div></div>";
			
		}
	}
		
	public static function deleteLink($element) {
		if ( preg_match('/(http|ftp|https)\:\/\/([^\s\[\]\"\'\(\)<（）。，]+)/', strval($element['content'])) == 0 ) {
			//echo 'delete' . $element['content'] . '<br/>';
			return FALSE;
		} else {
			return TRUE;
		}
	}
		
	public function actionFeedLink() {
		$i = 0;
		$feed_link = array();
		while(count($feed_link) < 20) {
			$feed=$this->makeStream($i++);
			$feed = array_filter($feed, array('StreamController','deleteLink'));
			$feed_link = array_merge($feed_link, $feed);
		}
	
		
		foreach ($feed_link as $s){
			$s['content'] = preg_replace ('/(^|[^\"\'\]])(http|ftp|https)\:\/\/([^\s\[\]\"\'\(\)<（）。，]+)/', '$1<a href="$2://$3" target="_blank">$2://$3</a>', $s['content']);
			echo "<div class='sweet ".$s['source']." clearfix'>";
			echo "<div class='avatar'><img src='".$s['avatar']."'></img></div>";
			echo "<div class='feed_content'>";
			echo "<div class='feeder_name'>".$s['user'].":</div>";
			echo "<div class='feeder_say'>".$s['content']."</div>";
			echo "<div class='feed_info'>".date('Y-m-d H:i:s',$s['datetime'])."</div>";
			echo "</div></div>";
		}
	}
	public function actionProfile()
	{
		echo "<xml>";
		$type;
		$string;
		$i=0;
		foreach ($this->services as $s){
			$type[]=$s->type;
			$service=new $s->type($s->param1,$s->param2);

			$this->addService($service);
		}
		foreach ($this->_services as $s){
			$id=$s->getMyID();
			$target=$type[$i];
			$string=$s->getProfile($target, $id);
			echo "<h1 id=".$i." name=".$target.">";
			echo "<div class=avatar>".$string[profile][avatar]."</div>";
			echo "<div class=username>".$string[profile][username]."</div>";
			echo '</h1>';
			$i++;
		}
//		$string=$this->getProfile(Douban, "http://api.douban.com/people/43674034");
		echo "</xml>";
		
	}

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}